package controllers;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

import play.Logger;
import play.db.jpa.JPABase;
import play.i18n.Messages;
import play.mvc.Before;
import play.mvc.Catch;
import play.mvc.Controller;
import play.mvc.Http.Header;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pany.domain.IConstant;
import com.pany.domain.Response;
import com.pany.domain.Result;
import com.pany.domain.models.Recharge;
import com.pany.domain.models.TranInfo;
import com.pany.domain.models.User;
import com.pany.domain.models.VIPInfo;
import com.pany.domain.req.AddRechargeReq;
import com.pany.domain.req.BatchAddTranReq;
import com.pany.exceptions.ServiceException;
import com.pany.utils.SessionUtil;

/**
 * 基本控制器
 * 
 * @author zengjie
 * 
 */
public class BaseController extends Controller
{
    private static final String I18N_PREFIX = "RESULTCODE_";
    
    private static final Gson gson;
    static
    {
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("yyyy-MM-dd hh:mm:ss");
        gson = builder.create();
    }
    
    protected static void renderFail(Response rsp, int code, Object... msgArgs)
    {
        if (rsp == null)
        {
            rsp = new Response();
        }
        Result result = new Result();
        result.setCode(code);
        result.setMessage(Messages.get(I18N_PREFIX + result.getCode(), msgArgs));
        rsp.setResult(result);
        renderJSON(gson.toJson(rsp));
    }
    
    protected static void renderSuccess(Response rsp)
    {
        if (rsp == null)
        {
            rsp = new Response();
        }
        Result result = new Result();
        result.setCode(IConstant.ICommonResultCode.SUCCESS);
        result.setMessage(Messages.get(I18N_PREFIX + result.getCode()));
        rsp.setResult(result);
        renderJSON(gson.toJson(rsp));
    }
    
    protected static <T> T readObject(Class<T> t)
    {
        String content;
        try
        {
            content = IOUtils.toString(request.body, "UTF-8");
        }
        catch (IOException e)
        {
            return null;
        }
        Logger.debug("Reuest Json:" + content);
        T obj = gson.fromJson(content, t);
        if (obj == null)
        {
            throw new ServiceException(IConstant.ICommonResultCode.PARAMTER_IS_NULL, "Request");
        }
        return obj;
    }
    
    protected static String getSid()
    {
        Header sid = request.headers.get(IConstant.ISysConstant.SESSION_ID_NAME);
        if (sid == null)
        {
            return null;
        }
        return sid.value();
    }
    

    
    protected static User getCurrentUser()
    {
        Header sid = request.headers.get(IConstant.ISysConstant.SESSION_ID_NAME);
        if (sid == null)
        {
            return null;
        }
        User user = SessionUtil.getAttr(getSid(), IConstant.ISysConstant.USER_SESSION_KEY);
        return user;
    }
    
    public static void catchAll()
    {
        renderFail(null, IConstant.ICommonResultCode.NO_FUNCTION_ERROR, request.path);
    }
    
    @Catch(value = {Exception.class})
    public static void exceptionHandle(Exception e)
    {
        JPABase.em().getTransaction().rollback();
        Logger.error(e, "handle request [" + request.path + "] occuring an error!");
        if (e instanceof ServiceException)
        {
            ServiceException se = (ServiceException)e;
            renderFail(null, se.getCode(), se.getErrorMsgArgs());
        }
        else if (e instanceof HibernateException)
        {
            renderFail(null, IConstant.ICommonResultCode.DATABASE_ERROR);
        }
        else
        {
            renderFail(null, IConstant.ICommonResultCode.SYSTEM_ERROR);
        }
        // throw new RuntimeException(e);
    }
    
    public static void main(String[] args)
    {
        AddRechargeReq reReq = new AddRechargeReq();
        reReq.setActualChargeCount(100D);
        reReq.setVipName("zhangsan");
        System.out.println(gson.toJson(reReq));
        
        BatchAddTranReq req = new BatchAddTranReq();
        List<String> infos = new ArrayList<String>();
        infos.add("3e6c1e86ba8845423e6c1e86ba884542");
        req.setTranTypeIdList(infos);
        VIPInfo vip = new VIPInfo();
        vip.setVipId("fc78e61fa6534c34fc78e61fa6534c34");
        vip.setPasswd("123456");
        req.setVipInfo(vip);
        System.out.println(gson.toJson(req));
    }
}
